/*
 * Copyright 2010 Aekold Helbrass
 * 
 * This file is part of RosterComposer.
 * 
 * RosterComposer is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * RosterComposer is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with RosterComposer.  If not, see <http://www.gnu.org/licenses/>.
 */
package org.heresylabs.rostercomposer;

import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.util.List;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSpinner;
import javax.swing.JTextField;
import javax.swing.SpinnerNumberModel;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import org.heresylabs.rostercomposer.roster.EntryNumberListener;
import org.heresylabs.rostercomposer.roster.EntryOptionsListener;
import org.heresylabs.rostercomposer.roster.RosterEntry;
import org.heresylabs.rostercomposer.units.Option;

/**
 *
 * @author Aekold Helbrass <Helbrass@gmail.com>
 */
public class UnitPanel extends JPanel implements ChangeListener, EntryNumberListener, EntryOptionsListener {

    private final Composer composer;
    private RosterEntry rosterEntry;
    private JTextField unitNameField = new JTextField();
    private JTextField unitCostField = new JTextField();
    private JSpinner numberSpinner;
    private JPanel optionsPanel = new JPanel(new GridBagLayout());
    private SpinnerNumberModel numberSpinnerModel = new SpinnerNumberModel();

    public UnitPanel(Composer composer) {
        this.composer = composer;
        setBorder(BorderFactory.createEmptyBorder(6, 6, 6, 6));
        //setBorder(BorderFactory.createCompoundBorder(BorderFactory.createEmptyBorder(6, 6, 6, 6), BorderFactory.createLineBorder(Color.BLUE)));
        setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));

        unitNameField.setEditable(false);
        unitCostField.setEditable(false);
        numberSpinnerModel.addChangeListener(this);

        super.add(createInfoPanel());
        //optionsPanel.setBorder(BorderFactory.createLineBorder(Color.DARK_GRAY));

        super.add(optionsPanel);
        super.add(Box.createVerticalGlue());
    }

    @Override
    public void stateChanged(ChangeEvent e) {
        if (rosterEntry == null) {
            return;
        }
        rosterEntry.setNumberAndUpdate(numberSpinnerModel.getNumber().intValue());
    }

    private void setupOptionsPanel() {
        try {
            optionsPanel.removeAll();
            List<Option> options = rosterEntry.getUnit().getOptions();
            if (options == null || options.isEmpty()) {
                return;
            }
            GridBagConstraints c = new GridBagConstraints();
            c.weightx = 0.5;
            c.weighty = 0.5;
            c.anchor = GridBagConstraints.BASELINE_LEADING;
            for (int i = 0; i < options.size(); i++) {
                Option option = options.get(i);
                c.gridy = i;
                OptionComponent component = OptionComponent.createOptionComponent(rosterEntry, option);
                optionsPanel.add(component, c);
            }
            optionsPanel.setMaximumSize(new Dimension(optionsPanel.getMaximumSize().width, optionsPanel.getPreferredSize().height));
        }
        finally {
            optionsPanel.updateUI();
        }
    }

    private JPanel createInfoPanel() {
        JPanel panel = new JPanel(new GridBagLayout());
        //panel.setBorder(BorderFactory.createLineBorder(Color.BLACK));

        numberSpinner = new JSpinner(numberSpinnerModel);
        Dimension size = new Dimension(50, numberSpinner.getMinimumSize().height);
        numberSpinner.setMinimumSize(size);
        numberSpinner.setPreferredSize(size);
        numberSpinner.setMaximumSize(size);

        GridBagConstraints c = new GridBagConstraints();
        c.anchor = GridBagConstraints.BASELINE_LEADING;
        c.insets = new Insets(0, 0, 6, 6);
        c.weighty = 0.5;
        panel.add(new JLabel("Name:"), c);
        c.gridy = 1;
        panel.add(new JLabel("Cost:"), c);
        c.gridy = 2;
        panel.add(new JLabel("Number:"), c);

        c.gridx = 1;
        c.weightx = 1;
        c.gridwidth = 2;
        c.fill = GridBagConstraints.HORIZONTAL;
        c.gridy = 0;
        panel.add(unitNameField, c);
        c.gridy = 1;
        panel.add(unitCostField, c);
        c.gridy = 2;
        c.gridwidth = 1;
        c.ipadx = 20;
        c.fill = GridBagConstraints.NONE;
        panel.add(numberSpinner, c);

        panel.setMaximumSize(new Dimension(panel.getMaximumSize().width, panel.getPreferredSize().height));

        return panel;
    }

    public RosterEntry getRosterEntry() {
        return rosterEntry;
    }

    private void fireNullingEntry() {
        unitNameField.setText(null);
        unitCostField.setText(null);
        numberSpinnerModel.removeChangeListener(this);
        numberSpinnerModel.setValue(0);
        numberSpinner.setEnabled(false);
        optionsPanel.removeAll();
        optionsPanel.updateUI();
    }

    public void setRosterEntry(RosterEntry rosterEntry) {
        if (this.rosterEntry != null && rosterEntry != this.rosterEntry) {
            // cleaning rosterEntry listeners:
            this.rosterEntry.removeNumberListener(this);
            this.rosterEntry.removeOptionListener(this);
        }

        if (rosterEntry == null) {
            fireNullingEntry();
            this.rosterEntry = null;
            return;
        }

        this.rosterEntry = rosterEntry;
        rosterEntry.addOptionsListener(this);
        rosterEntry.addNumberListener(this);
        {
            unitNameField.setText(rosterEntry.getUnit().getName());
            unitCostField.setText(String.valueOf(rosterEntry.calculateCost()));
        }
        {
            numberSpinnerModel.removeChangeListener(this);
            int min = rosterEntry.getUnit().getMinNumber();
            int max = rosterEntry.getUnit().getMaxNumber();
            numberSpinnerModel.setMinimum(min);
            numberSpinnerModel.setMaximum(max);
            if (min == max) {
                // we cannot change number, disabling spinner:
                numberSpinnerModel.setValue(min);
                numberSpinner.setEnabled(false);
            }
            else {
                numberSpinnerModel.setValue(rosterEntry.getNumber());
                numberSpinner.setEnabled(true);
            }
            numberSpinnerModel.addChangeListener(this);
        }
        setupOptionsPanel();
    }

    @Override
    public void fireNumberChanged(int number) {
        unitCostField.setText(String.valueOf(rosterEntry.getCost()));
        if (number != numberSpinnerModel.getNumber().intValue()) {
            numberSpinnerModel.setValue(number);
        }
    }

    @Override
    public void fireOptionChanged(Option option, boolean added) {
        unitCostField.setText(String.valueOf(rosterEntry.getCost()));
    }

}
